package com.sky.autofill;

import com.sky.context.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class CommonPropertyAutoFillAspect {
    @Pointcut(value = "@annotation(com.sky.autofill.AutoFill)")
    private void findFillMethod(){}

    //2通知
    @Before("findFillMethod()")
    public void autoFillValue(JoinPoint joinPoint) throws Exception {
        //1 获取新增对象
        Object[] args = joinPoint.getArgs();//获取对象参数
        //要求新增/修改时对象放在第一个位置
        Object arg = args[0];//获取对象参数的第一个属性

        //2.判断新增还是修改
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取增强方法上的注解
        AutoFill autoFillAnno = signature.getMethod().getAnnotation(AutoFill.class);
        //获取注解中携带的值INSERT或UPDATE
        String actionType = autoFillAnno.value();
        //给新增的属性赋值
        Method setCreateTime = arg.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
        Method setUpdateTime = arg.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
        Method setCreateUser = arg.getClass().getDeclaredMethod("setCreateUser", Long.class);
        Method setUpdateUser = arg.getClass().getDeclaredMethod("setUpdateUser", Long.class);
        if ("INSERT".equals(actionType)){
            setCreateTime.invoke(arg, LocalDateTime.now());
            setCreateUser.invoke(arg, BaseContext.getCurrentId());
            setUpdateTime.invoke(arg, LocalDateTime.now());
            setUpdateUser.invoke(arg, BaseContext.getCurrentId());
        }
        //给修改的属性赋值
        if ("UPDATE".equals(actionType)){
            setUpdateTime.invoke(arg, LocalDateTime.now());
            setUpdateUser.invoke(arg, BaseContext.getCurrentId());
        }

    }
}
